import React, { useState, useEffect } from "react";
import {
  Card,
  List,
  Space,
  Tag,
  Button,
  Input,
  Select,
  Empty,
  Spin,
  Modal,
  Form,
  message,
  Tooltip,
} from "antd";
import {
  MessageOutlined,
  LikeOutlined,
  EyeOutlined,
  UserOutlined,
  RobotOutlined,
  LockOutlined,
} from "@ant-design/icons";
import styled from "styled-components";
import type {
  DiscussionPost,
  DiscussionFilter,
  DiscussionStats,
} from "../../../../common/types/discussion";
import { useUser } from "../../../../../contexts/UserContext";
import PermissionGuard from "../../../../../components/PermissionGuard";
import discussionService from "../../../../../services/discussion";
import DiscussionDetail from "./DiscussionDetail";
import NewDiscussion from "./NewDiscussion";

const { Search } = Input;

const StyledCard = styled(Card)`
  margin-bottom: 24px;
  .ant-card-head-title {
    font-weight: bold;
  }
`;

const IconText = ({ icon, text }: { icon: React.ReactNode; text: string }) => (
  <Space>
    {icon}
    {text}
  </Space>
);

interface CourseDiscussionProps {
  courseId?: string;
}

const CourseDiscussion: React.FC<CourseDiscussionProps> = ({ courseId }) => {
  const { user } = useUser();
  const [loading, setLoading] = useState(false);
  const [discussions, setDiscussions] = useState<DiscussionPost[]>([]);
  const [stats, setStats] = useState<DiscussionStats>();
  const [filter, setFilter] = useState<DiscussionFilter>({
    sortBy: "latest",
  });
  const [selectedDiscussion, setSelectedDiscussion] = useState<string>();
  const [isNewDiscussionVisible, setIsNewDiscussionVisible] = useState(false);

  useEffect(() => {
    if (courseId) {
      loadDiscussions();
    }
  }, [courseId, filter]);

  const loadDiscussions = async () => {
    if (!courseId) return;

    setLoading(true);
    try {
      const { discussions: data } = await discussionService.getDiscussions(
        courseId,
        filter
      );
      setDiscussions(data);

      const statsData = await discussionService.getStats(courseId);
      setStats(statsData);
    } catch (error) {
      message.error("加载讨论列表失败");
      console.error("加载讨论列表失败:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = (value: string) => {
    setFilter({ ...filter, keyword: value });
  };

  const handleSortChange = (value: "latest" | "popular" | "mostReplies") => {
    setFilter({ ...filter, sortBy: value });
  };

  const handleTagClick = (tag: string) => {
    setFilter({
      ...filter,
      tags: filter.tags?.includes(tag)
        ? filter.tags.filter((t) => t !== tag)
        : [...(filter.tags || []), tag],
    });
  };

  const handleDiscussionClick = (discussionId: string) => {
    setSelectedDiscussion(discussionId);
  };

  const handleNewDiscussion = () => {
    setIsNewDiscussionVisible(true);
  };

  const handleNewDiscussionSubmit = async (values: {
    title: string;
    content: string;
    tags: string[];
  }) => {
    if (!courseId || !user) return;

    try {
      await discussionService.createDiscussion(courseId, {
        ...values,
        author: {
          id: user.id,
          name: user.name,
          role: user.role,
        },
      });
      message.success("发布成功！");
      setIsNewDiscussionVisible(false);
      loadDiscussions();
    } catch (error) {
      message.error("发布失败，请重试");
      console.error("发布讨论失败:", error);
    }
  };

  const handleLike = async (discussionId: string) => {
    if (!user) {
      message.warning("请先登录");
      return;
    }

    try {
      await discussionService.likeDiscussion(discussionId, user.id);
      loadDiscussions();
    } catch (error) {
      message.error("点赞失败，请重试");
      console.error("点赞失败:", error);
    }
  };

  return (
    <div>
      <Space direction="vertical" style={{ width: "100%", marginBottom: 16 }}>
        <Space>
          <Search
            placeholder="搜索讨论..."
            onSearch={handleSearch}
            style={{ width: 300 }}
          />
          <Select
            value={filter.sortBy}
            onChange={handleSortChange}
            style={{ width: 120 }}
            options={[
              { label: "最新", value: "latest" },
              { label: "最热", value: "popular" },
              { label: "最多回复", value: "mostReplies" },
            ]}
          />
          <PermissionGuard
            permission="discussion.create"
            fallback={
              <Tooltip title="需要登录后才能发起讨论">
                <Button icon={<LockOutlined />} disabled>
                  发起讨论
                </Button>
              </Tooltip>
            }
          >
            <Button type="primary" onClick={handleNewDiscussion}>
              发起讨论
            </Button>
          </PermissionGuard>
        </Space>

        <Space wrap>
          {["进程管理", "内存管理", "文件系统", "设备管理"].map((tag) => (
            <Tag
              key={tag}
              color={filter.tags?.includes(tag) ? "blue" : undefined}
              style={{ cursor: "pointer" }}
              onClick={() => handleTagClick(tag)}
            >
              {tag}
            </Tag>
          ))}
        </Space>
      </Space>

      <StyledCard>
        {loading ? (
          <div style={{ textAlign: "center", padding: "40px 0" }}>
            <Spin />
          </div>
        ) : discussions.length === 0 ? (
          <Empty description="暂无讨论" />
        ) : (
          <List
            itemLayout="vertical"
            dataSource={discussions}
            renderItem={(item) => (
              <List.Item
                key={item.id}
                actions={[
                  <IconText
                    icon={<EyeOutlined />}
                    text={item.views.toString()}
                    key="views"
                  />,
                  <PermissionGuard
                    permission="discussion.like"
                    fallback={
                      <Tooltip title="登录后即可点赞">
                        <IconText
                          icon={<LikeOutlined />}
                          text={item.likes.toString()}
                          key="likes"
                        />
                      </Tooltip>
                    }
                  >
                    <Button
                      type="link"
                      icon={<LikeOutlined />}
                      onClick={() => handleLike(item.id)}
                    >
                      {item.likes}
                    </Button>
                  </PermissionGuard>,
                  <IconText
                    icon={<MessageOutlined />}
                    text={item.replies.length.toString()}
                    key="replies"
                  />,
                ]}
                extra={
                  item.aiResponse && (
                    <Tag icon={<RobotOutlined />} color="purple">
                      AI已回复
                    </Tag>
                  )
                }
                onClick={() => handleDiscussionClick(item.id)}
              >
                <List.Item.Meta
                  title={item.title}
                  description={
                    <Space>
                      <UserOutlined />
                      {item.author.name}
                      <Tag
                        color={
                          item.author.role === "teacher" ? "blue" : undefined
                        }
                      >
                        {item.author.role === "teacher" ? "教师" : "学生"}
                      </Tag>
                      <span>发布于 {item.createTime}</span>
                      {item.tags.map((tag) => (
                        <Tag key={tag}>{tag}</Tag>
                      ))}
                    </Space>
                  }
                />
                {item.content}
              </List.Item>
            )}
          />
        )}
      </StyledCard>

      {selectedDiscussion && (
        <DiscussionDetail
          discussionId={selectedDiscussion}
          onClose={() => setSelectedDiscussion(undefined)}
        />
      )}

      <NewDiscussion
        visible={isNewDiscussionVisible}
        onCancel={() => setIsNewDiscussionVisible(false)}
        onSubmit={handleNewDiscussionSubmit}
      />
    </div>
  );
};

export default CourseDiscussion;
